import axios from 'axios';
import { ElMessage } from 'element-plus'

const TIMEOUT = 10000; // 默认超时时间为10秒


// 创建一个axios实例
const instance = axios.create({
  baseURL: '/api',
  // api的base_url
  timeout: TIMEOUT, // 请求超时时间
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
});
// 请求拦截器
instance.interceptors.request.use(
  config => {
    // 是否需要设置 token
    const isToken = (config.headers || {}).isToken === false
    // 在发送请求之前做些什么
    const token = localStorage.getItem('token');
    if (token && !isToken) {
      // 设置请求头token
      config.headers.Authorization = 'Bearer' + token;
    }
    return config;
  },
  error => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  response => {
    // 对响应数据做点什么
    if(response.config.url ==="/h5/api/login"){
      if(response.data.code ===200){
        ElMessage({
          message: 'success',
          type: 'success'
        })
        localStorage.setItem('token',response.data.data.token);
      }
    }
    //登录是否过期
    if(response.data.code ===424||response.code ===424){
      ElMessage({
        message: '令牌状态已过期，请重新登录',
        type: 'error'
      })
      localStorage.removeItem('token');
    }
    return response.data;
  },
  error => {
    // 对响应错误做点什么
    if (error.response) {
      switch (error.response.status) {
        case 424:
          // token过期或未登
          ElMessage({
            message: '令牌状态已过期，请重新登录',
            type: 'error'
          })
          localStorage.removeItem('token');
          break;
        case 404:
          // 资源不存在
          break;
        case 503:
          ElMessage({
            message: '服务器开小差啦',
            type: 'error'
          })
          break;
        default:
          break;
      }
    }
    return Promise.reject(error);
  }
);

export default {
  get(url, params = {}, timeout = TIMEOUT) {
    return instance.get(url, {
      params,
      timeout
    });
  },
  post(url, data = {}, timeout = TIMEOUT) {
    return instance.post(url, data, {
      timeout
    });
  },
  put(url, data = {}, timeout = TIMEOUT) {
    return instance.put(url, data, {
      timeout
    });
  },
  delete(url, params = {}, timeout = TIMEOUT) {
    return instance.delete(url, {
      params,
      timeout
    });
  }
};